<?php
declare(strict_types=1);

namespace App\Libs;

use function Hyperf\Support\env;

/**
 * 钉钉机器人消息通知
 * 文档地址：https://open.dingtalk.com/document/robots/customize-robot-security-settings
 */
class DingDing
{
    /**
     * 设置错误信息
     */
    public static function sendErrorMsg(string $errorMsg, string $errorType = 'Exception')
    {
        // 非正式环境不报错预警
        if (env('APP_ENV') !== 'prod') {
            // return;
        }

        // 增加记录：接口URI及请求参数
        $request = request();
        $requestUri = $request->path();
        if (!empty($requestUri)) {
            // 接口URI (path and query string)
            $errorMsg .= ",request_uri:" . $requestUri;
            // 接口请求参数 (post JSON)
            $postParams = $request->all();
            if (!empty($postParams)) {
                $errorMsg .= ",params:" . json_encode($postParams, JSON_UNESCAPED_UNICODE);
            }
        }

        // 消息内容
        $appName = env('APP_NAME', 'docker-jp12');
        $env = env('APP_ENV') === 'prod' ? $appName . '生产环境' : $appName . '开发环境';
        $msgData = [
            'msgtype' => 'markdown',
            'markdown' => [
                'title' => $appName . '程序异常通知',
                'text' => "#### 顺成脚本,异常请及时跟进处理。 \n "
                    . "> ###### 环境: <font color=#871F78>" . $env . "</font> \n "
                    . "> ###### 报错提示: <font color=#FF0000>" . $errorMsg . "</font> \n "
                    . "> ###### 报错类型: " . $errorType . " \n "
                    . "> ###### 报错时间: " . date("Y-m-d H:i:s")
            ]
        ];

        return self::msgPush($msgData);
    }

    /**
     * 将消息push到企业微信群
     * 注意：每个机器人每分钟最多发送20条。如果超过20条，会限流10分钟。
     */
    protected static function msgPush(array $msgData): bool
    {
        // 加签秘钥
        $secret = env('DINGDING_SCERET');
        // api地址
        $url = env('DINGDING_API_URL');
        // 当前毫秒时间戳
        $timestamp = intval(microtime(true) * 1000);
        // 加密sign
        // $hash = hash_hmac("sha256", utf8_encode("{$timestamp}\n{$secret}"), utf8_encode($secret), true);
        $hash = hash_hmac("sha256", mb_convert_encoding("{$timestamp}\n{$secret}", 'UTF-8', 'ISO-8859-1'), mb_convert_encoding($secret, 'UTF-8', 'ISO-8859-1'), true);
        $sign = urlencode(base64_encode($hash));
        // 拼接url
        $url .= '&timestamp=' . $timestamp . '&sign=' . $sign;
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
            curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json; charset=utf-8', 'timestamp:' . $timestamp, 'sign:' . $sign]);
            curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($msgData));
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
            // 成功返回{"errcode":0,"errmsg":"ok"}
            curl_exec($ch);
            curl_close($ch);
        } catch (\Exception $e) {
            return false;
        }
        return true;
    }
}
